package com.gz.im.backend.component.proxy;

import cn.hutool.json.JSONUtil;
import com.corundumstudio.socketio.SocketIOClient;
import com.gz.im.backend.component.manage.LocalCacheManage;
import com.gz.im.backend.component.manage.RedissonManage;
import com.gz.im.backend.pojo.MessageRequest;
import com.gz.im.backend.pojo.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.springframework.stereotype.Component;

/**
 * @author GuoZhong
 * @description Im事件代理
 * @date 2023/3/28 13:43
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AgentEventProxy {


	private final RedissonManage redissonManage;

	private final LocalCacheManage localCacheManage;



	/**
	 * 初始化连接
	 * @param uid
	 * @param client
	 */
	public void initOnConnect(Long uid, SocketIOClient client){
		localCacheManage.putAgent(uid,client);
		//加入坐席队列
		redissonManage.putAgentQueue(uid);
		//坐席注册成功动态生成订阅消息
		afterOnConnect(uid);
	}

	/**
	 *生成订阅消息
	 */
	private void afterOnConnect(Long uid) {
		RTopic rTopic = redissonManage.createTopic("topic:agent:"+uid);
		int listenerId = rTopic.addListener(MessageRequest.class, (charSequence, messageRequest) -> {
			log.info("接受到消息主题={}，内容={}", charSequence, messageRequest);
			sendMsgAgent(messageRequest);
		});
		//放置监听者id
		localCacheManage.putListen(uid,listenerId);

	}

	/**
	 * 初始化断开连接
	 * @param uid
	 */
	public void initOnDisconnect(Long uid){
        //删除坐席队列
		redissonManage.rmAgent(uid);
		//删除监听者id
		localCacheManage.rmListen(uid);
		//删除坐席
		localCacheManage.rmAgent(uid);
	}

	/**
	 * 坐席对话
	 * @param messageRequest
	 */
	public void AgentDialog(MessageRequest messageRequest){
		sendMsgClient(messageRequest);
	}
	/**
	 * 发送客户端
	 * @param messageRequest
	 */
	private void sendMsgClient(MessageRequest messageRequest) {
		log.info("发送客户端消息");
		User user = localCacheManage.getUser(messageRequest.getReceiverId());
		user.getClient().sendEvent("chat", JSONUtil.toJsonStr(messageRequest));
	}

	/**
     * 发送坐席端
     * @param
     */
	private void sendMsgAgent(MessageRequest request) {
		log.info("发送坐席端消息");
		SocketIOClient client = localCacheManage.getAgent(request.getReceiverId());
		client.sendEvent("chat", JSONUtil.toJsonStr(request));
	}




}
